<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="车辆管理"
      :indent="20"
      :columns="columns"
      :search-columns="searchColumns"
      :request-api="getTableList"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="'vehicle.info.create'" :icon="CirclePlus" @click="openAddEdit('新增车辆管理')">
          新增
        </el-button>
        <el-button
          v-auth="'vehicle.info.remove'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
        <!-- <el-button
          v-auth="'vehicle.info.import'"
          type="primary"
          :icon="Upload"
          plain
          @click="importData"
        >
          导入
        </el-button>
        <el-button
          v-auth="'vehicle.info.export'"
          type="primary"
          :icon="Download"
          plain
          @click="downloadFile"
        >
          导出
        </el-button> -->
      </template>
      <template #operation="{ row }">
        <el-button
          v-auth="'vehicle.info.update'"
          type="primary"
          link
          :icon="EditPen"
          @click="openAddEdit('编辑车辆管理', row, false)"
        >
          编辑
        </el-button>
        <el-button v-auth="'vehicle.info.remove'" type="primary" link :icon="Delete" @click="deleteInfo(row)"> 删除 </el-button>
      </template>
    </ProTable>
    <VehicleInfoForm ref="vehicleInfoRef" />
    <ImportExcel ref="ImportExcelRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, h } from 'vue';
import { CirclePlus, Delete, EditPen, Upload, Download } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import {
  createVehicleInfoApi,
  removeVehicleInfoApi,
  updateVehicleInfoApi,
  getVehicleInfoListApi,
  getVehicleInfoDetailApi,
  importVehicleInfoExcelApi,
  exportVehicleInfoExcelApi
} from '@/api/modules/vehicleinfo/vehicleInfo';
import { useHandleData } from '@/hooks/useHandleData';
import VehicleInfoForm from '@/views/vehicleinfo/vehicleInfo/components/VehicleInfoForm.vue';
import { useDictOptions } from '@/hooks/useDictOptions';
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface';
import type { VehicleInfoQuery, VehicleInfoRow } from '@/api/types/vehicleinfo/vehicleInfo';
import ImportExcel from '@/components/ImportExcel/index.vue';
import { downloadTemplate } from '@/api/modules/system/common';
import { useDownload } from '@/hooks/useDownload';
import { useDict } from '@/hooks/useDict';
defineOptions({
  name: 'VehicleInfoView'
});
// 使用useDict Hook 主动加载字典
useDict(['vehicle_type', 'dynamic_user_options']);
const proTableRef = ref<ProTableInstance>();
// 表格配置项
const columns: ColumnProps<VehicleInfoRow>[] = [
  { type: 'selection', width: 80 },
  { prop: 'vehicleNumber', label: '车辆编号' },
  {
    prop: 'driverName', 
    label: '司机姓名',
    width: 200,
    render: (scope: any) => {
      const { row } = scope;
      const scheduleType = row.scheduleType;
      
      // Create driver rows based on scheduleType
      const driverRows: string[] = [];
      
      if (scheduleType === '2001002') {
        // 2 rows for scheduleType 2001002
        driverRows.push(
          row.driverName || '',
          row.driverName2 || ''
        );
      } else if (scheduleType === '2001003') {
        // 3 rows for scheduleType 2001003
        driverRows.push(
          row.driverName || '',
          row.driverName2 || '',
          row.driverName3 || ''
        );
      } else {
        // Default single row
        driverRows.push(row.driverName || '');
      }
      
      // Use Vue 3 h() render function with inline styles
      return h('div', { 
        style: {
          display: 'flex',
          flexDirection: 'column',
          gap: '6px',
          padding: '4px 0'
        }
      }, 
        driverRows.map((driverName, index) => {
          if (!driverName.trim()) return null;
          
          const baseStyle = {
            display: 'flex',
            alignItems: 'center',
            padding: '4px 8px',
            border: '1px solid #dcdfe6',
            borderRadius: '4px',
            backgroundColor: '#f8f9fa',
            fontSize: '13px',
            color: '#303133',
            transition: 'all 0.2s ease',
            minHeight: '28px'
          };
          
          // Add specific styling based on driver number
          let driverStyle = {};
          
          if (index === 0) {
            driverStyle = {
              //borderLeft: '3px solid #67c23a',
              backgroundColor: '#f0f9ff'
            };
          } else if (index === 1) {
            driverStyle = {
              //borderLeft: '3px solid #409eff',
              backgroundColor: '#fde68a'
            };
          } else if (index === 2) {
            driverStyle = {
              //borderLeft: '3px solid #f56c6c',
              backgroundColor: '#fbcfe8'
            };
          }
          
          return h('div', {
            key: index,
            style: { ...baseStyle, ...driverStyle },
            onMouseenter: (e) => {
              const target = e.target as HTMLElement;
              if (target) {
                target.style.backgroundColor = '#e6f7ff';
                target.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
              }
            },
            onMouseleave: (e) => {
              const target = e.target as HTMLElement;
              if (target) {
                target.style.backgroundColor = index === 0 ? '#f0f9ff' : index === 1 ? '#ecf5ff' : '#fef0f0';
                target.style.boxShadow = 'none';
              }
            }
          }, `司机${index + 1}：${driverName}`);
        }).filter(Boolean)
      );
    }
  },
  { 
    prop: 'scheduleName', 
    label: '排班时间',
    width: 300,
    render: (scope: any) => {
      const { row } = scope;
      const scheduleType = row.scheduleType;
      
      // Create schedule time rows based on scheduleType
      const scheduleRows: Array<{time: string, name: string}> = [];
      
      if (scheduleType === '2001002') {
        // 2 rows for scheduleType 2001002
        scheduleRows.push(
          { time: row.scheduleTime1 || '', name: `${row.scheduleName} - 第一班` },
          { time: row.scheduleTime2 || '', name: `${row.scheduleName} - 第二班` }
        );
      } else if (scheduleType === '2001003') {
        // 3 rows for scheduleType 2001003
        scheduleRows.push(
          { time: row.scheduleTime1 || '', name: `${row.scheduleName} - 第一班` },
          { time: row.scheduleTime2 || '', name: `${row.scheduleName} - 第二班` },
          { time: row.scheduleTime3 || '', name: `${row.scheduleName} - 第三班` }
        );
      } else {
        // Default single row
        scheduleRows.push({ time: '', name: row.scheduleName || '' });
      }
      
      // Use Vue 3 h() render function with inline styles
      return h('div', { 
        style: {
          display: 'flex',
          flexDirection: 'column',
          gap: '8px',
          padding: '4px 0'
        }
      }, 
        scheduleRows.map((scheduleRow, index) => {
          const baseStyle = {
            display: 'flex',
            flexDirection: 'column',
            padding: '4px 6px',
            border: '1px solid #dcdfe6',
            borderRadius: '6px',
            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.05)',
            transition: 'all 0.2s ease',
            position: 'relative',
            cursor: 'pointer'
          };
          
          // Add specific styling based on shift number
          let shiftStyle = {};
          let shiftIcon = '';
          
          if (index === 0) {
            shiftStyle = {
              // borderLeft: '4px solid #67c23a',
              background: 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)'
            };
            // shiftIcon = '🌅 ';
          } else if (index === 1) {
            shiftStyle = {
              // borderLeft: '4px solid #409eff',
              background: 'linear-gradient(135deg, #fef3c7 0%, #fde68a 100%)'
            };
            // shiftIcon = '☀️ ';
          } else if (index === 2) {
            shiftStyle = {
              // borderLeft: '4px solid #f56c6c',
              background: 'linear-gradient(135deg, #fce7f3 0%, #fbcfe8 100%)'
            };
            // shiftIcon = '🌙 ';
          }
          
          return h('div', { 
            key: index, 
            style: { ...baseStyle, ...shiftStyle },
            onMouseenter: (e) => {
              const target = e.target as HTMLElement;
              if (target) {
                target.style.transform = 'translateY(-1px)';
                target.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.1)';
                target.style.borderColor = '#409eff';
              }
            },
            onMouseleave: (e) => {
              const target = e.target as HTMLElement;
              if (target) {
                target.style.transform = 'translateY(0)';
                target.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.05)';
                target.style.borderColor = '#dcdfe6';
              }
            }
          }, [
            h('div', { 
              style: {
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                width: '100%'
              }
            }, [
              h('div', { 
                style: {
                  fontWeight: '600',
                  color: '#2c3e50',
                  fontSize: '13px',
                  letterSpacing: '0.5px',
                  flex: '1'
                }
              }, shiftIcon + scheduleRow.name),
              scheduleRow.time ? h('div', { 
                style: {
                  color: '#6c757d',
                  fontSize: '12px',
                  fontWeight: '500',
                  fontFamily: 'Monaco, Consolas, monospace',
                  backgroundColor: 'rgba(255, 255, 255, 0.7)',
                  padding: '2px 6px',
                  borderRadius: '3px',
                  border: '1px solid rgba(0, 0, 0, 0.1)',
                  marginLeft: '8px'
                }
              }, scheduleRow.time) : null
            ].filter(Boolean))
          ].filter(Boolean));
        })
      );
    }
  },
  { prop: 'title', label: '名称' },
  { prop: 'sort', label: '排序' },
  {
    prop: 'vehicleTypeCd',
    label: '车辆类型 （字典表vehicle_type）',
    tag: true,
    enum: useDictOptions('vehicle_type'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  // { prop: 'isHidden', label: '是否隐藏' },
  // { prop: 'createTime', label: '创建时间' },
  // { prop: 'updateTime', label: '更新时间' },
  // {
  //   prop: 'createId',
  //   label: '创建人ID',
  //   tag: true,
  //   enum: useDictOptions('dynamic_user_options'),
  //   fieldNames: {
  //     label: 'codeName',
  //     value: 'id',
  //     tagType: 'callbackShowStyle'
  //   }
  // },
  // {
  //   prop: 'updateId',
  //   label: '更新人ID',
  //   tag: true,
  //   enum: useDictOptions('dynamic_user_options'),
  //   fieldNames: {
  //     label: 'codeName',
  //     value: 'id',
  //     tagType: 'callbackShowStyle'
  //   }
  // },
  { prop: 'parentDeptName', label: '公司' },
  { prop: 'deptName', label: '车队' },
  { prop: 'operation', label: '操作', width: 250, fixed: 'right' }
];
// 搜索条件项
const searchColumns: SearchProps[] = [
  { prop: 'vehicleNumber', label: '车辆编号', el: 'input' },
  { prop: 'title', label: '名称', el: 'input' },
  // { prop: 'sort', label: '排序', el: 'input' },
  {
    prop: 'vehicleTypeCd',
    label: '车辆类型',
    el: 'select',
    enum: useDictOptions('vehicle_type'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  // { prop: 'isHidden', label: '是否隐藏', el: 'input' },
  { prop: 'departmentId', label: '公司车队', el: 'input' }
];
// 获取table列表
const getTableList = (params: VehicleInfoQuery) => {
  let newParams = formatParams(params);
  return getVehicleInfoListApi(newParams);
};
const formatParams = (params: VehicleInfoQuery) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (newParams.createTime) {
    newParams.createTimeStart = newParams.createTime[0];
    newParams.createTimeEnd = newParams.createTime[1];
    delete newParams.createTime;
  }

  if (newParams.updateTime) {
    newParams.updateTimeStart = newParams.updateTime[0];
    newParams.updateTimeEnd = newParams.updateTime[1];
    delete newParams.updateTime;
  }

  if (newParams.deleteTime) {
    newParams.deleteTimeStart = newParams.deleteTime[0];
    newParams.deleteTimeEnd = newParams.deleteTime[1];
    delete newParams.deleteTime;
  }

  return newParams;
};
// 打开 drawer(新增、查看、编辑)
const vehicleInfoRef = ref<InstanceType<typeof VehicleInfoForm>>();
const openAddEdit = async (title: string, row: any = {}, isAdd = true) => {
  if (!isAdd) {
    const record = await getVehicleInfoDetailApi({ id: row?.id });
    row = record?.data;
  }
  const params = {
    title,
    row: { ...row },
    api: isAdd ? createVehicleInfoApi : updateVehicleInfoApi,
    getTableList: proTableRef.value?.getTableList
  };
  vehicleInfoRef.value?.acceptParams(params);
};
// 删除信息
const deleteInfo = async (params: VehicleInfoRow) => {
  await useHandleData(removeVehicleInfoApi, { ids: [params.id] }, `删除【${params.id}】车辆管理`);
  proTableRef.value?.getTableList();
};
// 批量删除信息
const batchDelete = async (ids: (string | number)[]) => {
  await useHandleData(removeVehicleInfoApi, { ids }, '删除所选车辆管理');
  proTableRef.value?.clearSelection();
  proTableRef.value?.getTableList();
};
// 导入
const ImportExcelRef = ref<InstanceType<typeof ImportExcel>>();
const importData = () => {
  const params = {
    title: '车辆管理',
    templateName: '车辆管理',
    tempApi: downloadTemplate,
    importApi: importVehicleInfoExcelApi,
    getTableList: proTableRef.value?.getTableList
  };
  ImportExcelRef.value?.acceptParams(params);
};
// 导出
const downloadFile = async () => {
  let newParams = formatParams(proTableRef.value?.searchParam as VehicleInfoQuery);
  useDownload(exportVehicleInfoExcelApi, '车辆管理', newParams);
};
</script>
